#-*- coding: utf-8 -*-
import time
import network
try:
    import uos as os
except ImportError:
    import os

class Initnet():
    '''初始化网络'''

    def __init__(self, config):
        self.config = config
        self.sta_if = network.WLAN(network.STA_IF)
        self.netconfig  = self.config['netconfig']
        self.localip = self.config['localip']
        try:
            os.mkdir('data')
        except:pass

    def write_ip(self):
        print('网络状态', self.sta_if.ifconfig())
        if self.sta_if.isconnected():
            wri_str = ''
            for item in self.sta_if.ifconfig():
                wri_str += item +'\n'

            try:
                fp = open(self.localip,'w')
            except:
                return False
            else:
                fp.write(wri_str)
                fp.close()
            del wri_str
            return True
        else:
            return False


    '''
    检测网络状态
    返回:
       True --  网络联通
       False -- 网络断开
    '''
    def main(self):
        equipm_file = self.config['equipm']
        equipm_nonull = False
        equipm_id = ''
        try:
            fp = open(equipm_file)
        except:
            equipm_nonull = False
        else:
            equipm_id = fp.read(-1)
            fp.close()
            equipm_id = equipm_id.strip()
            if equipm_id != '':
                equipm_nonull = True

        if not self.sta_if.isconnected():
            self.sta_if.active(True)
            file_str = ''
            try:
                fp = open(self.netconfig)
            except:
                file_str = ''
            else:
                file_str = fp.read(-1)
                fp.close()

            if len(file_str)>0:
                file_arr = file_str.split('\n')
                if len(file_arr)>0:
                    self.sta_if.connect(file_arr[0],file_arr[1])
                    time_i = 0
                    while not self.sta_if.isconnected():
                        time.sleep(1)
                        time_i += 1
                        if time_i > 30:
                            break

                    return self.write_ip(), equipm_nonull
            return False, equipm_nonull
        else:
            return self.write_ip(), equipm_nonull
